<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/3/14
 * Time: 14:28
 * @copyright: ©2024 永州微 聚商网络科技有限公司
 * @link: https://www.weijuyunKe.com

 */

namespace app\admin\controller;

use app\home\model\AmountLog;
use app\home\model\GoodsOrder;
use app\home\model\PackageOrder;
use app\home\model\PackageUseLog;
use app\home\model\UserPackage;
use app\Request;
use OSS\OssClient;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\facade\Filesystem;

class  Home
{


    public function orderStatistics(Request $request)
    {
        $where = [];
        if ( $request->staff_account['role_type'] == 3){
            $where['store_id'] = $request->staff_account['store_id'];
        }elseif ($request->staff_account['role_type'] == 2) {
            $where['staff_id'] = $request->staff_account['id'];
        }
        $amountLogModel = new AmountLog();
        // 今日充值
        $todayRechargeAmount = $amountLogModel
            ->where('operate_type' ,'in', [1,2,3,4,5,6,7])
            ->where($where)
            ->where('create_time', '>=', strtotime(date('Y-m-d 00:00:00')))->sum('amount');
        $monthRechargeAmount = $amountLogModel
            ->where('operate_type' ,'in', [1,2,3,4,5,6,7])->where(['type' => 1])
            ->where($where)
            ->where('create_time', '>=', strtotime(date('Y-m-01 00:00:00')))->sum( 'amount');


        $todayConsumptionAmount = $amountLogModel
            ->where('operate_type' ,'in', [8,9,10,11,12,13,14,15,16,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35])
            ->where($where)
            ->where(['status' => 1])
        ->where('create_time', '>=', strtotime(date('Y-m-d 00:00:00')))->sum('amount');

        $monthConsumptionAmount = $amountLogModel
            ->where('operate_type' ,'in', [8,9,10,11,12,13,14,15,16,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35])
            ->where($where)
            ->where(['status' => 1])
            ->where('create_time', '>=', strtotime(date('Y-m-01 00:00:00')))->sum('amount');

        $goodsOrderModel = new GoodsOrder();
        $todayOrderCount = $goodsOrderModel
            ->where($where)->where('create_time', '>=', strtotime(date('Y-m-d 00:00:00')))
            ->where('status', '=', 6)->count();
        $monthOrderCount = $goodsOrderModel
            ->where($where)->where('create_time', '>=', strtotime(date('Y-m-01 00:00:00')))
            ->where('status', '=', 6)->count();

       // $todayOrderCount += $packageOrderModel->where('create_time', '>=', strtotime(date('Y-m-d 00:00:00')))
          //  ->where('status', '=', 3)->count();
       // $monthOrderCount += $packageOrderModel->where('create_time', '>=', strtotime(date('Y-m-01 00:00:00')))
        //    ->where('status', '=', 3)->count();
        return adminSuccess('统计数据', [
            'todayRechargeAmount' => $todayRechargeAmount,
            'monthRechargeAmount' => $monthRechargeAmount,
            'todayConsumptionAmount' => $todayConsumptionAmount,
            'monthConsumptionAmount' => $monthConsumptionAmount,
            'todayOrderCount' => $todayOrderCount,
            'monthOrderCount' => $monthOrderCount,
        ]);
    }

    public function amountStatistics(Request $request)
    {
        $param = $request->param();
        $amountLogModel = new AmountLog();
        $where = [];
        $diff = strtotime($param['end_time']) - strtotime($param['start_time']);
        $days_diff = ceil($diff / (60 * 60 * 24)); // 60秒 * 60分钟 * 24小时 = 1天
        for ($i = 0; $i <= $days_diff; $i++) {
            $key = date('Y-m-d', strtotime($param['start_time']) + (60 * 60 * 24 * $i));
            $rechargeAmount[$key] = ['amount' => 0, 'datetime' => $key];
            $consumptionAmount[$key] = ['amount' => 0, 'datetime' => $key];
            $packageCount[$key] = ['count' => 0, 'datetime' => $key];
        }
        if ( $request->staff_account['role_type'] == 3){
            $where['store_id'] = $request->staff_account['store_id'];
        }elseif ($request->staff_account['role_type'] == 2) {
            $where['staff_id'] = $request->staff_account['id'];
        }
        $rechargeData = $amountLogModel
            ->field("sum(amount) as  amount,date_format(from_unixtime(create_time), '%Y-%m-%d') as dateTime")
            ->where('create_time', '>=', strtotime($param['start_time']))
            ->where('create_time', '<=', strtotime($param['end_time']) . '23:59:59')
            ->where($where)
            ->where('operate_type' ,'in', [1,2,3,4,5,6,7])
            ->group("dateTime")
            ->select()->toArray();
        foreach ($rechargeData as $value) {
            if (array_key_exists($value['dateTime'], $rechargeAmount)) {
                $rechargeAmount[$value['dateTime']]['amount'] = $value['amount'];
            }
        }
        $data['recharge_data'] = array_values($rechargeAmount);
        $consumptionData= $amountLogModel->field("sum(amount) as  amount,date_format(from_unixtime(create_time), '%Y-%m-%d') as dateTime")
            ->where('create_time', '>=', strtotime($param['start_time']))
            ->where($where)
            ->where('create_time', '<=', strtotime($param['end_time']) . '23:59:59')
            ->where('operate_type' ,'in', [8,9,10,11,12,13,14,15,16,21,22,23,24,25,26,27])
            ->where(['status' => 1])
            ->group("dateTime")
            ->select()->toArray();
        foreach ($consumptionData as $value) {
            if (array_key_exists($value['dateTime'], $consumptionAmount)) {
                $consumptionAmount[$value['dateTime']]['amount'] = bcadd($value['amount'], $consumptionAmount[$value['dateTime']]['amount'], 2);
            }
        }
        $data['consumption_amount'] = array_values($consumptionAmount);
        $packageUseLog = new PackageUseLog();
        $packageData = $packageUseLog->field("count(id) as count ,date_format(from_unixtime(create_time), '%Y-%m-%d') as dateTime")
            ->where('create_time', '>=', strtotime($param['start_time']))
            ->where($where)
            ->where('create_time', '<=', strtotime($param['end_time'] . '23:59:59'))
            ->group("dateTime")
            ->select()->toArray();
        foreach ($packageData as $value) {
            if (array_key_exists($value['dateTime'], $packageCount)) {
                $packageCount[$value['dateTime']]['count'] = $value['count'];
            }
        }
        $data['package_count'] = array_values($packageCount);
        return adminSuccess('k线', $data);
    }

    public function payWayStatistics(Request $request)
    {
        $param = $request->param();
        $amountLogModel = new AmountLog();
        $payWay = $param['type'];
        $where = [];
        if ( $request->staff_account['role_type'] == 3){
            $where['store_id'] = $request->staff_account['store_id'];
        }elseif ($request->staff_account['role_type'] == 2) {
            $where['staff_id'] = $request->staff_account['id'];
        }
        if ($payWay == 1) { // 在线支付
            $data['weixin'] = ['amount' => 0, 'proportion' => 0];
            $data['yuer'] = ['amount' => 0, 'proportion' => 0];
            $amountData = $amountLogModel
                ->where('pay_type' ,'in',[3,4])
                ->where($where)
                ->field("sum(amount) as  amount,pay_type")
                ->where('status','=',1)
                ->group('pay_type')
                ->select()->toArray();

            if ($amountData){
                $amountDataByPayType = array_column($amountData,null,'pay_type');
                $data['weixin']['amount'] = isset($amountDataByPayType['3'])? $amountDataByPayType['3']['amount']:0;
                $data['yuer']['amount'] =  isset($amountDataByPayType['4'])? $amountDataByPayType['4']['amount']:0;
                $totalAmount =  bcadd($data['weixin']['amount'], $data['yuer']['amount'],2);
                if ($totalAmount){
                    $data['weixin']['proportion'] = bcmul(bcdiv(  $data['weixin']['amount'],$totalAmount,2),100,2);
                    $data['yuer']['proportion'] = bcmul(bcdiv(   $data['yuer']['amount'],$totalAmount,2),100,2);
                }
            }
        } else {
            $data['weixin'] = ['amount' => 0, 'proportion' => 0];
            $data['alipay'] = ['amount' => 0, 'proportion' => 0];
            $data['xianjin'] = ['amount' => 0, 'proportion' => 0];
            $data['pos'] = ['amount' => 0, 'proportion' => 0];
            $amountData = $amountLogModel
                ->where('pay_type' ,'=', 2)
                ->field("sum(amount) as  amount,pay_method")
                ->where('status','=',1)
                ->where($where)
                ->where('operate_type' ,'in', [8,10,11,12,13,14,15,16,21,22,23,24,25,26,27])
                ->group('pay_method')
                ->select()->toArray();
            if ($amountData){
                $amountDataByPayType = array_column($amountData,null,'pay_method');
                $data['weixin']['amount'] = isset($amountDataByPayType['1'])? $amountDataByPayType['1']['amount']:0;;
                $data['alipay']['amount'] =  isset($amountDataByPayType['2'])? $amountDataByPayType['2']['amount']:0;;
                $data['xianjin']['amount'] = isset($amountDataByPayType['3'])? $amountDataByPayType['3']['amount']:0;;
                $data['pos']['amount'] =  isset($amountDataByPayType['5'])? $amountDataByPayType['5']['amount']:0;;
                $amountArray = array_column($amountData, 'amount');
                $totalAmount = array_sum($amountArray);
                if ($totalAmount){
                    $data['weixin']['proportion'] = bcmul(bcdiv( $data['weixin']['amount'],$totalAmount,2),100,2);
                    $data['alipay']['proportion'] = bcmul(bcdiv( $data['alipay']['amount'],$totalAmount,2),100,2);
                    $data['xianjin']['proportion'] =bcmul(bcdiv( $data['xianjin']['amount'],$totalAmount,2),100,2);
                    $data['pos']['proportion'] =  bcmul(bcdiv( $data['pos']['amount'],$totalAmount,2),100,2);
                }
            }
        }

        return adminSuccess('统计', $data);
    }

    public function packageStatistics(Request $request)
    {
        $packageOrder = new PackageOrder();
        $where = [];
        if ( $request->staff_account['role_type'] == 3){
            $where['store_id'] = $request->staff_account['store_id'];
        }elseif ($request->staff_account['role_type'] == 2) {
            $where['staff_id'] = $request->staff_account['id'];

        }
        $packageInfo = $packageOrder->where($where)->where(['status' => 3])->field('count(id) as count,sum(price) as price')->find();
        $packageUser = new UserPackage();
        $packageNum = $packageUser->where('order_id', '>', 0)
            ->field('count(id) as count,sum(total_num) as total_num ,sum(num) as num')->find();
        $info['order_count'] = $packageInfo['count'];
        $info['order_amount'] = $packageInfo['price'];
        $info['surplus_num'] = $packageNum['num'];
        $info['num'] = $packageNum['total_num'] - $packageNum['num'];
        return adminSuccess('套餐卡', $info);

    }

    public function financeStatistics(Request $request)
    {
        $param = $request->param();
        $amountLogModel = new AmountLog();
        $shaomaTotal = $zaixianTotal = $xianxiaTotal = 0;
        if ($param['time_type'] =='month '){
            $field  ="sum(amount) as  amount,date_format(from_unixtime(create_time), '%Y-%m-%d') as dateTime";
            $diff = strtotime($param['end_time']) - strtotime($param['start_time']);
            $days_diff = ceil($diff / (60 * 60 * 24)); // 60秒 * 60分钟 * 24小时 = 1天
            for ($i = 0; $i <= $days_diff; $i++) {
                $key = date('Y-m-d', strtotime($param['start_time']) + (60 * 60 * 24 * $i));
                $zaixianAmount[$key] = ['amount' => 0, 'datetime' => $key];
                $shaomaAmount[$key] = ['amount' => 0, 'datetime' => $key];
                $xianxiaAmount[$key] = ['amount' => 0, 'datetime' => $key];
            }
        }else{
            $field  ="sum(amount) as  amount,date_format(from_unixtime(create_time), '%Y-%m-%d %H:00:00') as dateTime";
            for ($i = 0; $i <= 6; $i++) {
                $zaixianAmount[$i] = $xianxiaAmount[$i] = $shaomaAmount[$i] = ['amount' => 0, 'datetime' => $i * 4,];
            }
        }
        $group = 'dateTime';
        if ($param['type'] == '1') {  // 充值
            $shaomaWhere = [['pay_type','=',1],
               ['operate_type','in',[6,7]]
            ];
            $xianxiaWhere = [['pay_type','=',2],
                ['operate_type','in',[2,3,4,5]]
            ];
            $zaixianWhere = [['pay_type','=',3],
                ['operate_type','=',1]
            ];
        } else {
            $shaomaWhere = [['pay_type','=',1],
                ['operate_type','in',[16,17,26,27]]
            ];
            $xianxiaWhere = [['pay_type','=',2],
                ['operate_type','in',[12,13,14,15,22,23,24,25]]
            ];
            $zaixianWhere = [['pay_type','=',3],
                ['operate_type','in',[10,8]],
                ['status','=',1]
            ];
        }

        if ( $request->staff_account['role_type'] == 3){
            $shaomaWhere[] = ['store_id','=',$request->staff_account['store_id']];
            $xianxiaWhere[] = ['store_id','=',$request->staff_account['store_id']];
            $zaixianWhere[] = ['store_id','=',$request->staff_account['store_id']];
        }elseif ($request->staff_account['role_type'] == 2) {
            $shaomaWhere = ['staff_id' ,'=',$request->staff_account['id']];
            $xianxiaWhere[] = ['staff_id','=',$request->staff_account['id']];
            $zaixianWhere[] = ['staff_id','=',$request->staff_account['id']];
        }
        $shaomaData = $amountLogModel->byTimeStatistics($shaomaWhere,$field,$group);
        $xianxiaData = $amountLogModel->byTimeStatistics($xianxiaWhere,$field,$group);
        $zaixianData = $amountLogModel->byTimeStatistics($zaixianWhere,$field,$group);
        if ($param['time_type'] =='month ') {
            foreach ($shaomaData as $value) {
                if (array_key_exists($value['dateTime'], $shaomaData)) {
                    $shaomaAmount[$value['dateTime']]['amount'] = bcadd($value['amount'], $shaomaAmount[$value['dateTime']]['amount'], 2);
                }
                $shaomaTotal = bcadd($value['amount'], $shaomaTotal, 2);
            }
            foreach ($zaixianData as $value) {
                if (array_key_exists($value['dateTime'], $zaixianAmount)) {
                    $zaixianAmount[$value['dateTime']]['amount'] = bcadd($value['amount'], $zaixianAmount[$value['dateTime']]['amount'], 2);
                }
                $zaixianTotal = bcadd($value['amount'], $zaixianTotal, 2);
            }
            foreach ($xianxiaData as $value) {
                if (array_key_exists($value['dateTime'], $xianxiaAmount)) {
                    $xianxiaAmount[$value['dateTime']]['amount'] = bcadd($value['amount'], $xianxiaAmount[$value['dateTime']]['amount'], 2);
                }
                $shaomaTotal = bcadd($value['amount'], $shaomaTotal, 2);
            }
        }else{
            foreach ($zaixianData as $value) {

                if (date('H', strtotime($value['dateTime'])) / 4 > 0) {
                    $zaixianAmount[ceil(date('H', strtotime($value['dateTime'])) / 4)]['amount'] =
                        bcadd($value['amount'], $zaixianAmount[ceil(date('H', strtotime($value['dateTime'])) / 4)]['amount'], 2);
                }
                $zaixianTotal = bcadd($value['amount'], $zaixianTotal, 2);
            }
            foreach ($shaomaData as $value) {
                if (date('H', strtotime($value['dateTime'])) / 4 > 0) {
                    $shaomaAmount[ceil(date('H', strtotime($value['dateTime'])) / 4)]['amount'] =
                        bcadd($value['amount'], $shaomaAmount[ceil(date('H', strtotime($value['dateTime'])) / 4)]['amount'], 2);
                }
                $shaomaTotal = bcadd($value['amount'], $shaomaTotal, 2);
            }
            foreach ($xianxiaData as $value) {
                if (date('H', strtotime($value['dateTime'])) / 4 > 0) {
                    $xianxiaAmount[ceil(date('H', strtotime($value['dateTime'])) / 4)]['amount'] =
                        bcadd($value['amount'], $xianxiaAmount[ceil(date('H', strtotime($value['dateTime'])) / 4)]['amount'], 2);
                }
                $xianxiaTotal = bcadd($value['amount'], $xianxiaTotal, 2);
            }
        }

        $data['zaixian_amount'] = array_values($zaixianAmount);
        $data['xianxia_amount'] = array_values($xianxiaAmount);
        $data['shaoma_amount'] = array_values($shaomaAmount);
        $data['zaixian_total'] = $zaixianTotal;
        $data['xianxia_total'] = $xianxiaTotal;
        $data['shaoma_total'] = $shaomaTotal;
        return adminSuccess('统计', $data);
    }

    public function amountTotal(Request $request)
    {

        $param = $request->param();
        $amountLogModel = new AmountLog();
        $rechargeTotalWhere = $rechargeTodayWhere = $rechargeYesterdayWhere = [
            ['operate_type', 'in', [1,2,3,4,5,6,7]]
        ];
        if (isset($param['start_time']) && !empty($param['start_time'])) {
            $rechargeTotalWhere[] = ['create_time', '>=', $param['start_time']];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])) {
            $rechargeTotalWhere[] = ['create_time', '<=', $param['end_time']];
        }
        if ( $request->staff_account['role_type'] == 3){
            $rechargeTotalWhere[] = ['store_id','=',$request->staff_account['store_id']];
            $rechargeTodayWhere[] = ['store_id','=',$request->staff_account['store_id']];
            $rechargeYesterdayWhere[] = ['store_id','=',$request->staff_account['store_id']];
        }elseif ($request->staff_account['role_type'] == 2) {
            $rechargeTotalWhere = ['staff_id' ,'=',$request->staff_account['id']];
            $rechargeTodayWhere[] = ['staff_id','=',$request->staff_account['id']];
            $rechargeYesterdayWhere[] = ['staff_id','=',$request->staff_account['id']];
        }

        $rechargeTodayWhere[] = ['create_time', '>=', strtotime(date('Y-m-d 00:00:00'))];
        $rechargeYesterdayWhere[] = ['create_time', '>=', strtotime("yesterday")];
        $rechargeYesterdayWhere[] = ['create_time', '<', strtotime(date('Y-m-d 00:00:00'))];
        $rechargeTotal = $amountLogModel->where($rechargeTotalWhere)->sum('amount');
        $rechargeToday = $amountLogModel->where($rechargeTodayWhere)->sum('amount');
        $rechargeYesterday = $amountLogModel->where($rechargeYesterdayWhere)->sum('amount');
        $goodsTotalWhere[] = ['status', '=', 6];
        $goodsTodayWhere[] = ['status', '=', 6];
        $goodsYesterdayWhere[] = ['status', '=', 6];
        $goodsTodayWhere[] = ['create_time', '>=', strtotime(date('Y-m-d 00:00:00'))];
        $goodsYesterdayWhere[] = ['create_time', '>=', strtotime("yesterday")];
        $goodsYesterdayWhere[] = ['create_time', '<', strtotime(date('Y-m-d 00:00:00'))];
        if (isset($param['start_time']) && !empty($param['start_time'])) {
            $goodsTotalWhere[] = ['create_time', '>=', $param['start_time']];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])) {
            $goodsTotalWhere[] = ['create_time', '<=', $param['end_time']];
        }

        $goodsOrderModel = new GoodsOrder();
        $goodsTotal = $goodsOrderModel->where($goodsTotalWhere)->sum('reality_amount');
        $goodsToday = $goodsOrderModel->where($goodsTodayWhere)->sum('reality_amount');
        $goodsYesterday = $goodsOrderModel->where($goodsYesterdayWhere)->sum('reality_amount');
        $packageTotalWhere = $packageTodayWhere = $packageYesterdayWhere = [
            ['operate_type', 'in', [10,11,12,13,14,15,16,17]]
        ];
        if (isset($param['start_time']) && !empty($param['start_time'])) {
            $packageTotalWhere[] = ['create_time', '>=', $param['start_time']];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])) {
            $packageTotalWhere[] = ['create_time', '<=', $param['end_time']];
        }
        if ( $request->staff_account['role_type'] == 3){
            $packageTotalWhere[] = ['store_id','=',$request->staff_account['store_id']];
            $packageTodayWhere[] = ['store_id','=',$request->staff_account['store_id']];
            $packageYesterdayWhere[] = ['store_id','=',$request->staff_account['store_id']];
        }elseif ($request->staff_account['role_type'] == 2) {
            $packageTotalWhere = ['staff_id' ,'=',$request->staff_account['id']];
            $packageTodayWhere[] = ['staff_id','=',$request->staff_account['id']];
            $packageYesterdayWhere[] = ['staff_id','=',$request->staff_account['id']];
        }

        $packageTodayWhere[] = ['create_time', '>=', strtotime(date('Y-m-d 00:00:00'))];
        $packageYesterdayWhere[] = ['create_time', '>=', strtotime("yesterday")];
        $packageYesterdayWhere[] = ['create_time', '<', strtotime(date('Y-m-d 00:00:00'))];

        $packageTotal = $amountLogModel->where($packageTotalWhere)->sum('amount');
        $packageToday = $amountLogModel->where($packageTodayWhere)->sum('amount');
        $packageYesterday = $amountLogModel->where($packageYesterdayWhere)->sum('amount');

        $userTotalWhere = $userTodayWhere = $userYesterdayWhere = [
            /*    ['status' ,'=' ,1]*/
        ];
        if (isset($param['start_time']) && !empty($param['start_time'])) {
            $userTotalWhere[] = ['create_time', '>=', $param['start_time']];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])) {
            $userTotalWhere[] = ['create_time', '<=', $param['end_time']];
        }

        $userTodayWhere[] = ['create_time', '>=', strtotime(date('Y-m-d 00:00:00'))];
        $userYesterdayWhere[] = ['create_time', '>=', strtotime("yesterday")];
        $userYesterdayWhere[] = ['create_time', '<', strtotime(date('Y-m-d 00:00:00'))];

        $userModel = new \app\home\model\User();
        $userTotal = $userModel->where($userTotalWhere)->count();
        $userToday = $userModel->where($userTodayWhere)->count();
        $userYesterday = $userModel->where($userYesterdayWhere)->count();

        $data = [
            'recharge_total' => $rechargeTotal,
            'recharge_today' => $rechargeToday,
            'recharge_yesterday' => $rechargeYesterday,
            'goods_total' => $goodsTotal,
            'goods_today' => $goodsToday,
            'goods_yesterday' => $goodsYesterday,
            'package_total' => $packageTotal,
            'package_today' => $packageToday,
            'package_yesterday' => $packageYesterday,
            'user_total' => $userTotal,
            'user_today' => $userToday,
            'user_yesterday' => $userYesterday,
        ];
        return adminSuccess('统计', $data);

    }

    public function payWay(Request $request)
    {
        $param = $request->param();
        $totalAmount = 0;
        $data['weixin']['amount'] = 0;
        $data['apiPay']['amount'] = 0;
        $data['xianjin'] ['amount'] = 0;
        $data['yuer']['amount'] = 0;
        $data['pos']['amount'] = 0;
        $where =[];
        if ( $request->staff_account['role_type'] == 3){
            $where['store_id'] = $request->staff_account['store_id'];
        }elseif ($request->staff_account['role_type'] == 2) {
            $where['staff_id'] = $request->staff_account['id'];

        }

        if ($param['type'] == 1) { // 商城
            $goodsOrderModel = new GoodsOrder();
            $orderData = $goodsOrderModel
                ->where(['status' => 6])
                ->where($where)
                ->field('sum(reality_amount) as amount , pay_way as pay_type')
                ->group('pay_type')
                ->select()->toArray();
        } else {
            $PackageOrderModel = new PackageOrder();
            $orderData = $PackageOrderModel
                ->where($where)
                ->where(['status' => 3])->field('sum(price) as amount , pay_type  ')
                ->group('pay_type')
                ->select()->toArray();
        }
        if ($orderData) {
            foreach ($orderData as $value) {
                $totalAmount = bcadd($totalAmount, $value['amount'], 2);
                if ($value['pay_type'] == 2 || $value['pay_type'] == 3 || $value['pay_type'] == 7) {
                    $data['weixin']['amount'] = bcadd($data['weixin']['amount'], $value['amount'], 2);
                }
                if ($value['pay_type'] == 4 || $value['pay_type'] == 8) {
                    $data['apiPay']['amount'] = bcadd($data['apiPay']['amount'], $value['amount'], 2);
                }

                if ($value['pay_type'] == 1) {
                    $data['yuer']['amount'] = bcadd($data['yuer']['amount'], $value['amount'], 2);
                }
                if ($value['pay_type'] == 4) {
                    $data['xianjin']['amount'] = bcadd($data['xianjin']['amount'], $value['amount'], 2);
                }
                if ($value['pay_type'] == 6) {
                    $data['pos']['amount'] = bcadd($data['pos']['amount'], $value['amount'], 2);
                }

            }
        }
        if ($totalAmount) {
            $data['weixin']['proportion'] = bcdiv($data['weixin']['amount'], $totalAmount, 2);
            $data['apiPay']['proportion'] = bcdiv($data['apiPay']['amount'], $totalAmount, 2);
            $data['xianjin'] ['proportion'] = bcdiv($data['xianjin']['amount'], $totalAmount, 2);
            $data['yuer']['proportion'] = bcdiv($data['yuer']['amount'], $totalAmount, 2);
            $data['pos']['proportion'] = bcdiv($data['pos']['amount'], $totalAmount, 2);
        } else {
            $data['weixin']['proportion'] = 0;
            $data['apiPay']['proportion'] = 0;
            $data['xianjin'] ['proportion'] = 0;
            $data['yuer']['proportion'] = 0;
            $data['pos']['proportion'] = 0;
        }


        $dataSort = array_column($data, 'amount');
        array_multisort($dataSort, SORT_DESC, $data);
        return adminSuccess('支付排行', $data);
    }

    public function statistics(Request $request)
    {
        $amountLogModel = new AmountLog();
        $where = [];
        if ( $request->staff_account['role_type'] == 3){
            $where['store_id'] = $request->staff_account['store_id'];
        }elseif ($request->staff_account['role_type'] == 2) {
            $where['staff_id'] = $request->staff_account['id'];

        }
        $data['recharge'] = $amountLogModel
            ->where('operate_type' ,'in' ,[1,2,3,4,5,6,7])
            ->sum('amount');
        $userModel = new \app\home\model\User();

        $data['balance'] = $userModel->sum('balance');
        $goodsOrderModel = new GoodsOrder();
        $data['goods_order_number'] = $goodsOrderModel->where(['status' => 6])->where($where)->count();
        $packageOrderModel = new PackageOrder();
        $data['package_order_number'] = $packageOrderModel->where($where)->where(['status' => 3])->count();
        $amountModel = new AmountLog();
        $data['consumption_amount'] =   $amountModel->where($where)
            ->where('status','=',1)
            ->where('operate_type' ,'in' ,[8,9,10,11,12,13,14,15,16,17,21,22,23,24,25,26,27,28,29,30,21,32,33,34,35])->sum('amount');;

        return adminSuccess('统计', $data);

    }

    public function upload(Request $request)
    {


        $configModel = new \app\home\model\Config();
        $value = $configModel::getConfigValue('upload_way');
        $files = $request->file("file");
        if (!$files) {
            return adminError('请上传文件');
        }
        $ext = $files->extension();

        $size = filesize($files);


        if ($value == 1 || $ext == 'pem') {
            try {
                if ($ext == 'pem'){
                    $tempFile = $_FILES['file']['tmp_name'];
                    $targetFile = './uploads/' . date('YmdHis').$_FILES['file']['name'];
                    if (move_uploaded_file($tempFile, $targetFile)) {
                        return adminSuccess('上传成功', ['url' => $targetFile]);
                    } else {
                        return adminError('上传失败');
                    }
                }else{
                    $path = 'uploads';
                    // 将图片保存至本地
                    $saveName = Filesystem::disk('public')->putFile($path, $files);
                    $saveName = $request->domain() . '/storage/' . $saveName;
                    return adminSuccess('上传成功', ['url' => $saveName]);
                }

                //将文件上传的路径返回
            } catch (\think\exception\ValidateException $e) {
                return adminError($e->getMessage());
            }
        } else if ($value == 2) {
            $fileType = $configModel::getConfigValue('qiniu_file_type');
            if ($fileType) {
                $fileTypeArray = explode(',', $fileType);
                if (!in_array($ext, $fileTypeArray)) {
                    return adminError('此类型文件不允许上传');
                }
            }

            $qiniu_access_key = $configModel::getConfigValue('qiniu_access_key');
            $qiuniu_secret_bucket = $configModel::getConfigValue('qiniu_secret_key');
            $qiniu_bucket = $configModel::getConfigValue('qiniu_bucket');

            // 构建Auth对象
            $auth = new Auth($qiniu_access_key, $qiuniu_secret_bucket);

            // 要上传的空间
            $bucket = $qiniu_bucket;
            // 生成上传Token
            $token = $auth->uploadToken($bucket);

            // 上传到七牛后的文件名
            $key = date('Y-m-d') . '/' . substr(md5($files->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $files->extension();

            // 初始化UploadManager类
            $uploadMgr = new UploadManager();
            list($ret, $err) = $uploadMgr->putFile($token, $key, $files->getRealPath());
            if ($err !== null) {
                adminError('上传失败');
            } else {
                return adminSuccess('上传成功', ['url' => $configModel::getConfigValue('qiniu_domin') . '/' . $ret['key']]);
            }
        } else {
            $fileType = $configModel::getConfigValue('ali_file_type');
            $fileTypeArray = explode(',', $fileType);
            if (!in_array($ext, $fileTypeArray)) {
                return adminError('此类型文件不允许上传');
            }
            $accessKeyId = $configModel::getConfigValue('ali_access_key');
            $accessKeySecret = $configModel::getConfigValue('ali_secret_key');
            $endpoint = $configModel::getConfigValue('ali_domain');
            $bucket = $configModel::getConfigValue('ali_bucket');
            //实例化对象 将配置传入
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

            //这里是有sha1加密 生成文件名 之后连接上后缀
            $key = date('Y-m-d') . '/' . substr(md5($files->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $files->extension();
            //上传至阿里云的目录 为年+月/日的格式
            //执行阿里云上传 bucket名称,上传的目录,文件
            $result = $ossClient->uploadFile($bucket, $key, $files->getRealPath());

            //将结果输出
            return adminSuccess('上传成功', ['url' => $result['info']['url']]);

        }
    }

    public function rechargeStatistics(Request $request)
    {
        $param = $request->param();
        $amountLogModel = new AmountLog();
        $packageOrderwhere[] = ['status', '=', 3];
        $where = [];
        if ( $request->staff_account['role_type'] == 3){
            $where[] = ['store_id', '=', $request->staff_account['store_id']];
            $packageOrderwhere[] = ['store_id', '=', $request->staff_account['store_id']];

        }elseif ($request->staff_account['role_type'] == 2){
            $packageOrderwhere[] = ['staff_id', '=', $request->staff_account['staff_id']];
            $where[] = ['staff_id', '=', $request->staff_account['id']];
        }
        if (isset($param['start_time']) && !empty($param['start_time'])) {
            $where[] = ['create_time', '>=', strtotime($param['start_time'])];
            $packageOrderwhere[] = ['create_time', '>=', strtotime($param['start_time'])];

        }
        if (isset($param['end_time']) && !empty($param['end_time'])) {
            $where[] = ['create_time', '<=', strtotime($param['end_time'] . '23:59:59')];
            $packageOrderwhere[] = ['create_time', '<=', strtotime($param['end_time'] . '23:59:59')];
        }
        $data['total_amount'] = $amountLogModel
            ->where('operate_type' ,'in' ,[1,2,3,4,5,6,7])
            ->where($where)->sum('amount');

        $data['zaixian_amount'] = $amountLogModel
            ->where('operate_type' ,'=' ,1)
            ->where($where)->sum('amount');

        $data['shaoma_amount'] = $amountLogModel  ->where('operate_type' ,'in' ,[6,7])
            ->where($where)->sum('amount');

        $data['xianxia_amount'] = $amountLogModel
            ->where('operate_type' ,'in' ,[2,3,4,5])
            ->where($where)->sum('amount');


        $packageOrder = new PackageOrder();

        $data['package_count'] = $packageOrder->where($packageOrderwhere)->count();
        $data['polymerization_wechat']  = $amountLogModel
            ->where($where)
            ->where('operate_type','=', 29)
            ->sum('amount');
        $data['polymerization_ali']  = $amountLogModel
            ->where($where)
            ->where('operate_type','=', 28)
            ->sum('amount');

        return adminSuccess('统计', $data);
    }


}